#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include<stdlib.h>

void GetNext(char*sub, int*next,int lenSub)
{
	next[0] = -1;
	next[1] = 1;
	int i = 2;
	int k = 0;

	while (i<lenSub)
	{
		if (k==-1||sub[i-1]==sub[k])
		{
			next[i] = k + 1;
			k++;
			i++;
		}
		else
		{
			k = next[k];
		}
	}

}

int KMP(char*str, char*sub, int pos)
{
	assert(str != NULL&&sub != NULL);
	int lenStr = strlen(str);
	int lenSub = strlen(sub);
	int i = pos;
	int j = 0;
	int*next = (int*)malloc(sizeof(int)*lenSub);

	GetNext(sub, next,lenSub);
	if (lenStr==0||lenSub==0)
	{
		return -1;
	}

	if (pos<0)
	{
		return -1;
	}

	while (i<lenStr&&j<lenSub)
	{
		
		if (str[i] == sub[j])
		{
			i++;
			j++;	
		}
		else
		{
			j = next[j];
		}
	}
	if (j>=lenSub)
	{
		return i - j;

	}
	return -1;

}



int main()
{

	printf("%d\n", KMP("ababcabcdabcde", "abcd", 0));


	return 0;
}